namespace Xmef.Engine
{
    using System;
    using System.Globalization;
    using Xmef.Interfaces;
    using Xmef.Library;

    [Serializable]
    public class PluginManager : IPluginManager
    {
        private readonly IPluginHostManager _hostManager;

        public PluginManager()
        {
            this._hostManager = new PluginHostManager();
        }

        public IPluginHostManager HostManager
        {
            get
            {
                return this._hostManager;
            }
        }

        public IPluginConfiguration LoadServiceProvider<T>(string hostName, string fileName, bool isDefault) where T : class, IPluginServiceProvider<T>
        {
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, ">>> {0}", typeof(T).Name));
            IPluginConfiguration configuration = PluginHostManager.LoadHost<T>(this._hostManager, hostName, fileName, isDefault);
            PluginHostManager.RegisterServiceProvider<T>(this._hostManager);
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "<<< {0}", typeof(T).Name));
            return configuration;
        }

        public void UnloadServiceProvider<T>(IPluginConfiguration configuration) where T : class, IPluginServiceProvider<T>
        {
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, ">>> {0}", typeof(T).Name));
            PluginHostManager.UnloadHost<T>(this._hostManager, configuration);
            PluginHostManager.UnregisterServiceProvider<T>(this._hostManager);
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "<<< {0}", typeof(T).Name));
        }

        public IPluginConfiguration Load<T>(string hostName, string fileName, bool isDefault)
        {
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, ">>> {0}", typeof(T).Name));
            IPluginConfiguration configuration = PluginHostManager.LoadHost<T>(this._hostManager, hostName, fileName, isDefault);
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "<<< {0}", typeof(T).Name));
            return configuration;
        }

        public void Unload<T>(IPluginConfiguration configuration)
        {
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, ">>> {0}", typeof(T).Name));
            PluginHostManager.UnloadHost<T>(this._hostManager, configuration);
            LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "<<< {0}", typeof(T).Name));
        }
    }
}

